package com.hm.health.Utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.hm.health.entity.arguments.StartArgumentsManager;
import com.hm.health.service.RawdataUploadService;

public class NetStateUtil {
    protected Context mContext;
    protected BroadcastReceiver mReceiver;
    private final String TAG = "NetStateUtil";

    public NetStateUtil(Context mContext) {
        this.mContext = mContext;

        //registerNetReceiver();
    }

    public void registerNetReceiver() {
        if (null == mContext)
            return;

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                if (null == info) {
                    // Toast.makeText(context, "no network", Toast.LENGTH_SHORT).show();
                } else {
                    switch (info.getType()) {
                        case ConnectivityManager.TYPE_WIFI:
                            // Toast.makeText(context, "wifi", Toast.LENGTH_SHORT).show();
                            break;
                        case ConnectivityManager.TYPE_MOBILE:
                            // Toast.makeText(context, "mobile", Toast.LENGTH_SHORT).show();
                            break;
                    }

                    if (info.isConnected()) {
                        triggerUpload();
                    }
                }
            }
        };

        mContext.registerReceiver(mReceiver, intentFilter);
    }

    public void unregisterNetReceiver() {
        if (null == mContext || null == mReceiver)
            return;
        mContext.unregisterReceiver(mReceiver);
    }

    protected void triggerUpload() {
        String functionName = StartArgumentsManager.getInstance().getFunctionName();
        if (null == functionName || functionName.isEmpty()) {
            return;
        }
        String fileDir = Constans.ECG_FLASH_DATA_ROOT;
        RawdataUploadService.uploadExtDir(mContext, fileDir);
    }
}
